package cn.wolfcode.trip.app.web.controller;

import cn.wolfcode.trip.app.util.FreemarkerUtil;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.RegionQueryObject;
import cn.wolfcode.trip.base.query.StrategyQueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IStrategyService;
import cn.wolfcode.trip.base.service.ITravelService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//区域资源控制器
@RestController
@RequestMapping("/regions")
public class RegionController {
    @Autowired
    private IRegionService regionService;
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private ITravelService travelService;
    @Autowired
    private ServletContext ctx;

    /*
        查询所有区域
        动作:GET
        资源:/regions
        参数:
     */
    @GetMapping
    public Object list() {
        return regionService.list();
    }


    /*
        查询热门区域
        动作:GET
        资源:/regions/hots
        参数:state=1
     */
    @GetMapping("/hots")
    public Object listHot(Integer state) {
        return regionService.listByState(state);

    }

    /*
        查询当前区域攻略
        动作:GET
        资源:/regions/{regionId}/strategies
        参数:
     */
    @GetMapping("/{regionId}/strategies")
    public void listHot(StrategyQueryObject qo, HttpServletResponse resp)
            throws Exception {
        //获取模板路径
        String dir = ctx.getRealPath("/template");
        //设置响应类型
        resp.setContentType("text/html;charset=UTF-8");

        Map<String, Object> map = new HashMap<>();
        map.put("id", qo.getRegionId());

        //查询该区域所有攻略,带分页
        qo.setState(-1);
        PageInfo<Strategy> pageInfo = strategyService.query(qo);
        map.put("info", pageInfo);

        //如果当前页不是第一页,说明当前是在翻页
        if (qo.getCurrentPage() > 1) {
            FreemarkerUtil.wirteTempData(dir,"classify.ftl",
                    map, resp.getWriter());
            return;
        }

        //查询该区域推荐攻略,不分页
        qo.setPageSize(0);
        //设置查询推荐攻略
        qo.setState(Strategy.STATE_COMMEND);
        List<Strategy> commends = strategyService.query(qo).getList();
        //把需要返回的对象封装到map中再返回
        map.put("commends", commends);

        FreemarkerUtil.wirteTempData(dir,"strategyContent.ftl",
                map, resp.getWriter());
    }



}
